<?

/*
*
*   Excalibur Content Management System
*   Copyright © 2008 Egor "Sontan" Kuryanovich
*
*   Based on Explay Engine v2.0 by Golovdinov Alexander
*
*   Official site: www.excms.ru
*   Contact e-mail: support@excms.ru
*
*   GNU General Public License original source:
*   http://www.gnu.org/licenses/gpl-3.0.html
*
*/

if ($EXCMS != 'work') {
	header ('Location: ../../index.php');
	exit;
}

// Загружаем настройки модуля и экспортируем их
$options = file ($_SERVER['DOCUMENT_ROOT'].'/'."modules/articles/admin/options.txt");
$art_options = array ();
foreach ($options as $opt) 
{
	$opt = explode ("=", $opt);	
	$art_options[$opt[0]] = $opt[1];
}


include $_SERVER['DOCUMENT_ROOT'].'/modules/articles/module.php';

if (isset($_GET['cat'])) $cat = addslashes($_GET['cat']);
if (isset($_GET['id'])) $id = intval ($_GET['id']);

$order = 'art_id';

if (isset($_GET['id']) || isset($_GET['url'])) 
{
	$option = "art_id = '$id'";
	if (!isset($_GET['id']) && preg_match("#^[a-z0-9_-]+$#", $_GET['url'])) 
	{
		$url = htmlspecialchars ($_GET['url']);
		$option = "art_url_name = '$url'";
	}
	
	$GET_ARTICLE = $db->query ("SELECT a.*, auto_tag, u.user_name, ac.cat_header, ac.cat_description, ac.cat_users, ac.cat_rating, ac.cat_id 
		FROM ".DB_PEREFIX."_articles AS a 
		JOIN ".DB_PEREFIX."_users AS u ON (a.art_author = u.user_id)
		LEFT JOIN ".DB_PEREFIX."_art_category AS ac ON (a.art_category = ac.cat_name)
		WHERE $option");
			
	if ($db->num_rows($GET_ARTICLE) == 1) 
	{
		$article = $db->fetch_array ($GET_ARTICLE);
		
		$body = $article['art_body'];
		
		if ($article['auto_tag'] == "yes") $body = n2br($body);
		//else $body = $article['art_body'];
		
		$body = input_video (replace_symbols ($body));
		
		// Если пост должен вести себя как станица
		if ($article['art_like_page'] == "yes") 
		{
			past_table ($article['art_header'], $body);
		}
		else 
		{
			// ========================================
			print $template->display ('art_panel.tpl');
					
		
			$PAGE_TITLE = $article['art_header'].' / ';
			
			if ($article['cat_header'] == '')
				$PAGE_TITLE .= 'Персональный блог "'.$article['user_name'].'"';
			else
				$PAGE_TITLE .= $article['cat_header'];
				
				
			$options = "";
			if (in_blog($article['cat_id'])) 
				$options .= str_replace ('{ID}', $article['cat_id'], get_element ('{exit_blog}', '{/exit_blog}'));
			elseif (is_registered()) 
				$options .= str_replace ('{ID}', $article['cat_id'], get_element ('{join_blog}', '{/join_blog}'));
		
			// Если коллективный блог то выводим информацию о блоге
			if ($article['cat_id'] != '')
			{
				$blog_karma = $article['cat_rating'];
		
				// HACK:  
				if (!is_registered() || my_karma() < 0 || isset($_COOKIE['blog_'.$article['art_category']])) 
					$karma_bar = $template->display ('articles/blog_karma_cant.tpl', false);
				elseif ($blog_karma >= 0) 
					$karma_bar = $template->display ('articles/blog_karma_good.tpl', false);
				else 
					$karma_bar = $template->display ('articles/blog_karma_bad.tpl', false);

		
				($article['cat_users'] == '')	
					? $usrs = 0 
					: $usrs = $article['cat_users'];
		
				$template->set_var ('{BLOG_USERS}', $usrs);

				(file_exists ('images/blogs/'.$article['art_category'].'.jpg')) 
					? $template->set_var ('{BLOG_AVATAR}', '/images/blogs/'.$article['art_category'].'.jpg') 
					: $template->set_var ('{BLOG_AVATAR}', '/images/noavatar.gif');

				$template->set_var ('{OPTIONS}', $options);
		
				$blog_panel = $template->display ('articles/blog_info.tpl', false);
			}
			else
			{
				// Если блог персональный
			}	
		
		
			// Выводим содержимое поста
			$template->set_var ("{RATING}", print_rating ($id, $article['art_rating'], $article['art_author'], $article['art_voters']));			
			$template->set_var ("{HEADER}", $article['art_header']);

			$template->set_var ("{BODY}", $body);
			$template->set_var ("{DATE}", format_time($article['art_date']));
			$template->set_var ("{ART_ID}", $id);
			$template->set_var ("{AUTHOR_ID}", $article['art_author']);
			$template->set_var ("{AUTHOR_NAME}", $article['user_name']);
			$template->set_var ("{TAGS}", print_tags ($article['art_tags']));
			if ($article['art_image'] != "") 
				$template->set_var ("{IMAGE}", "<a href=\"/{$article['art_image']}\" target=\"_blank\"><img src=\"/thumbs.php?x=200&y=200&url={$article['art_image']}\" align=\"left\" alt=\"{$article['art_header']}\"></a>");
			else 
				$template->set_var ("{IMAGE}", "");
	
			$template->set_var ("{BLOG_INFO}", $blog_panel);
			$template->set_var ("{BLOG_KARMA}", $karma_bar);
			$template->set_var ("{BLOG_KARMA_VALUE}", number_format ($blog_karma, 2, ',', ''));
			$template->set_var ("{BLOG_NAME}", $article['art_category']);
			$template->set_var ("{BLOG_HEADER}", $article['cat_header']);
			$template->set_var ("{BLOG_DESC}", $article['cat_description']);
		
		
			print $template->display ("articles/big_article.tpl");
		
			// Если присланы данные для удаления комментария
			if ($_GET['del_com'] == "true" && isset ($_GET['com_id'])) 
				delete_comment($_GET['com_id']);

			// Если прислан комментарий то добавляем его
			if (isset($_POST['com_body'])) 
			{
				add_comment ($_POST['com_name'], $_POST['com_mail'], $_POST['com_body'], 'articles', $id, $_POST['code']);
			}
		
			print '<a name="comments"></a><div id="comments_div">';
			print_comments ('articles', $id, '/articles/'.$id.'.html');
			print '</div>';
			
			if ($article['art_comments'] == 'on') past_com_table ('/articles/'.$id.'.html#comments');
			if (isset($_POST['com_body'])) 
			echo '<script type="text/javascript">
						document.getElementById("new_comment").style.display = "";
						document.getElementById("com_body").value = "";
					</script>';
		
			// ========================================
		}
	}
	else error_404 ();
}
// Если открыта закладка поиска по тэгам
elseif (isset ($_GET['cat']) && $_GET['cat'] == 'tags') 
{
	// Формируем меню навигации
	if (!isset($_GET['user'])) 
	{
		past_navblock (array (
							array ('Написать статью', '/my_articles/add/', 'cat', 'add'),
							array ('Поиск по тегам', '/articles/tags/', 'cat', 'tags'),
							array ('Комментарии', '/art_comments/', 'name', 'art_comments'),
							array ('TOP блогов', '/top/', 'name', 'top'),		
							)
					);
	}
	
	// Выводим форму поиска по тэгам
	echo '<div id="tag_search">
	<form method="get" action="/articles/">
		<img src="/themes/'.$theme.'/images/cloud.gif" /> 
		<input type="text" name="tagname" id="tagname" value="'.$_GET['tagname'].'" />
	</form>
	</div>';
	
	$get_tags = $db->query ("SELECT art_tags FROM ".DB_PEREFIX."_articles ORDER BY art_id DESC LIMIT 70;");
	$count = $db->num_rows ($get_tags);
	
	$all_tags = '';
	while (list ($tags) = $db->fetch_row ($get_tags)) 
	{
		if (trim ($tags) != '') 
		{
			$tag = explode (',', $tags);
			
			for ($i=0; $i<count($tag); $i++) 
				$all_tags .= strtolower (trim ($tag[$i])).',';
		}
	}

	if (substr($all_tags, strlen($all_tags)-1) == ',') 
		$all_tags = substr($all_tags, 0, strlen($all_tags)-1);
	
	$tags = 0;
	$tags = explode (',', $all_tags);
	$tag_count = array ();
	$tagname = array ();
	$unique_tags = array ();
	$count = count($tags);
	
	for ($i=0; $i<$count; $i++) 
	{
		$like = 0;
		for ($c=0; $c<count($unique_tags); $c++) if ($tags[$i] == $unique_tags[$c]) $like++;
		if ($like == 0) array_push ($unique_tags, $tags[$i]);
	}
	
	for ($i=0; $i<count($unique_tags);  $i++) 
	{
		$tag = trim ($unique_tags[$i]);
		$tag_count[$i] = 0;
		for ($c=0; $c<$count; $c++) if ($tag == trim($tags[$c])) $tag_count[$i]++;
		$tagname[$i] = $tag_count[$i].".".$tag;
	}
	sort ($tagname);
	$tagname = array_reverse ($tagname);
	$tags = array ();
	
	for ($i=0; $i<count($tagname); $i++) {
		array_push ($tags, $tagname[$i]);
		if ($i == 69) break;
	}
	
	$tagname = array ();
	for ($i=0; $i<count($tags); $i++) {
		$part = explode (".", $tags[$i]);
		array_push ($tagname, $part[1].".".$part[0]);
	}
	sort ($tagname);
	
	$tag_count = array ();
	$tag_name = array ();
	for ($i=0; $i<count($tagname); $i++) {
		$part = explode (".", $tagname[$i]);
		array_push ($tag_name, $part[0]);
		array_push ($tag_count, $part[1]);
	}
	
	$content = '<span class="cloud">';
	for ($i=0; $i<count($tagname); $i++) {
		$size = 31;
		for ($c=0; $c<count($tagname); $c++) if ($tag_count[$i] < $tag_count[$c]) $size -= 4;
		if ($size < 8) $size = 8;
		$content .= "\n<a href=\"/articles/?tagname=".urlencode($tag_name[$i])."\" style=\"font-size:{$size}px;\">{$tag_name[$i]}</a> ";
	}
	$content .= '</span>';
	past_table ('Облако тегов статей', $content);
}
else 
{

	// Формируем меню навигации
	if (!isset($_GET['user'])) 
	{
		past_navblock (array (
							array ('Написать статью', '/my_articles/add/', 'cat', 'add'),
							array ('Поиск по тегам', '/articles/tags/', 'cat', 'tags'),
							array ('Комментарии', '/art_comments/', 'name', 'art_comments'),
							array ('TOP блогов', '/top/', 'name', 'top'),		
							)
					);
	}

	past_articles ();	
}


